#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/1 13:37
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : BaseModel.py
# @Software: PyCharm
# @FileDescription：通用模型类对象

import re
from datetime import datetime
from sqlalchemy import Column, DateTime, VARCHAR, BigInteger
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import as_declarative, declared_attr


@as_declarative()
class BaseModel:
    """
    通用字段创建
    """
    id = Column(BigInteger, primary_key=True, index=True, autoincrement=True, comment="ID")
    create_by = Column(VARCHAR(255), nullable=True, default="", comment="创建人")
    update_by = Column(VARCHAR(255), nullable=True, default="", comment="更新人")
    create_time = Column(DateTime, default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                         server_default=func.now(), comment="创建时间")
    update_time = Column(DateTime, default=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                         onupdate=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), server_default=func.now(),
                         server_onupdate=func.now(), comment="更新时间")
    __name__: str

    @declared_attr
    def __tablename__(cls) -> str:
        # 如果没有指定tablename，则默认使用model类名转换为表名字
        name_list = re.findall(r"[A-Z][a-z\d]*", cls.__name__)
        # 表明格式替换成下划线格式 如 MallUser -> mall_user
        return "_".join(name_list).lower()


@as_declarative()
class BaseNullModel:
    """
    通用空字段配置
    """
    __name__: str

    @declared_attr
    def __tablename__(cls) -> str:
        # 如果没有指定tablename，则默认使用model类名转换为表名字
        name_list = re.findall(r"[A-Z][a-z\d]*", cls.__name__)
        # 表明格式替换成下划线格式 如 MallUser -> mall_user
        return "_".join(name_list).lower()


